package userModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/jwts"
	"KumquatDrivesServices/model"
	"regexp"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type UserRegisteredRequest struct {
	UserRequest
	NickName string `json:"nickName" binding:"required"`
}

func (UserModuleApi) UserRegistered(c *gin.Context) {
	var req UserRegisteredRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	// 校验邮箱格式
	emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9.]+$`)
	if !emailRegex.MatchString(req.UserEmail) {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	// 校验用户名是否已存在
	var UserModule model.UserModel
	err := global.DB.Where("user_email = ?", req.UserEmail).First(&UserModule).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		logrus.Errorf("Query user error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if err == nil {
		res.FailWithCode(res.USER_EXIST, c)
		return
	}
	//加密密码
	password, hashPwdErr := HashPwd(req.Password)
	if hashPwdErr != nil {
		logrus.Errorf("Hash password error: %v", hashPwdErr)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	// 注册用户
	user := model.UserModel{
		UserEmail:          req.UserEmail,
		Password:           password,
		NickName:           req.NickName,
		UserAvatar:         "",
		TotalCapacity:      1024 * 1024 * 1024, // 默认1G
		CapacityUsed:       0,
		TimeOfRegistration: time.Now().Unix(),
	}
	err = global.DB.Create(&user).Error
	if err != nil {
		logrus.Errorf("Create user error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	//签发Token
	accessToken, refreshToken, GenerateTokenErr := jwts.GenerateToken(user.ID)
	if GenerateTokenErr != nil {
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	c.Header("accessToken", accessToken)
	c.Header("refreshToken", refreshToken)
	if CacheErr := user.CacheUserInfo(); CacheErr != nil {
		logrus.Errorf("cache user info error: %v", CacheErr)
	}
	res.OkWithData(user, c)
}
